package com.lris.handle;

import com.alibaba.fastjson2.JSON;
import com.lris.enumerates.CommandType;
import com.lris.pojodata.Command;
import com.lris.rest.Result;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class WebsocketHandle extends SimpleChannelInboundHandler<TextWebSocketFrame>  {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
        //格式化成json


        log.info("接收到的消息code"+frame.text());
        try {
            Command command = JSON.parseObject(frame.text(), Command.class);
            log.info("接收到的消息"+command.getCode());
            switch (CommandType.math(command.getCode())){
                case CONNECTION ->ConnectionHandle.execute(ctx,command);
                //聊天  code 为 10002
                case CHAT -> ChatHandle.execute(ctx,frame);
                //群聊  code 为 10003
                case JOIN -> JoinHandle.execute(ctx);
                //添加好友 code 为100
                case ADD -> UserHandle.execute(ctx,frame);
                default -> ctx.channel().writeAndFlush(Result.fail("不支持的code类型"));
            }
        } catch (Exception e) {
            ctx.channel().writeAndFlush(Result.fail(e.getMessage()));
            throw new RuntimeException(e.getMessage());
        }
    }
}
